package com.pay.util;

import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.config.RequestConfig;
/**
 * 发起http请求的工具类
 * 设个类的使用可以参考httpClient文档
 * 去httpClient官网下载一个，里面就有examples
 * */
public class HttpHelper {
	
	//内部类，如果发生异常将抛出此类
	public static class HttpApiException extends RuntimeException {
		private static final long serialVersionUID = 1L;
		private Object code;

		public Object getCode() {
			return code;
		}
		public HttpApiException(Object code,String message) {
			super(message);
			this.code = code;
		}
	}
	//关闭http请求资源用的函数
	private void closeHttpReuqest(CloseableHttpResponse response,CloseableHttpClient httpClient) {
		//关闭资源
		try {
			if(response != null) {
				response.close();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
	//设置超时
	private void setRequestConfig(HttpRequestBase request) {
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
		request.setConfig(requestConfig);
	}
	//添加http请求头
	protected void addHeaders(HttpRequestBase request,Map<String,String> headers) {
		if(headers != null) {
			for(Map.Entry<String, String> item : headers.entrySet()) {
				request.addHeader(item.getKey(), item.getValue());
			}
		}
	}
	//从response中获取结果
	protected String getResponse(CloseableHttpResponse response,CloseableHttpClient httpClient) {
		int status = -1;
		String result;
		try {
			HttpEntity entity = response.getEntity();
			if(entity==null) return "";
			status = response.getStatusLine().getStatusCode();
			result = EntityUtils.toString(entity,"UTF-8");
			EntityUtils.consume(entity);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			closeHttpReuqest(response, httpClient);
		}
		if(status != 200 && status != 201 && status != 204) {
			throw new HttpApiException(status,result);
		}
		return result;
	}
	//Delete请求，返回字符串
	public String httpDeleteRequest(String url,Map<String,String> headers) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpDelete httpDelete = new HttpDelete(url);
		setRequestConfig(httpDelete);
		CloseableHttpResponse response = null;
		try {
			addHeaders(httpDelete,headers);
			response = httpClient.execute(httpDelete);
		} catch(Exception e) {
			closeHttpReuqest(response, httpClient);
			throw new RuntimeException(e);
		}
		return getResponse(response, httpClient);
	}
	//get请求，返回字符串
	public String httpGetRequest(String url,Map<String,String> headers) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		setRequestConfig(httpGet);
		CloseableHttpResponse response = null;
		try {
			addHeaders(httpGet,headers);
			response = httpClient.execute(httpGet);
		} catch(Exception e) {
			closeHttpReuqest(response, httpClient);
			throw new RuntimeException(e);
		}
		return getResponse(response, httpClient);
	}
	//http请求返回字符串
	public String httpPostRequest(String url,String body, Map<String,String> headers) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		setRequestConfig(httpPost);
		CloseableHttpResponse response = null;
		try {
			if(body != null) {
				StringEntity entity = new StringEntity(body,"UTF-8");
				httpPost.setEntity(entity);
			}
			addHeaders(httpPost,headers);
			response = httpClient.execute(httpPost);
		} catch (Exception e) {
			closeHttpReuqest(response, httpClient);
			throw new RuntimeException(e);
		}
		return getResponse(response, httpClient);
	}
}
